#include <iostream>
#include <thread>
#include <vector>

#include "../inc/memPool.h"

using namespace memoryPoolV1;

// examples

class P1 {
    int id_;
};

class P2 {
    int id_[5];
};

class P3 {
    int id_[10];
};

class P4 {
    int id_[20];
};

void BenchmarkMemoryPool(std::size_t ntimes, std::size_t nworks, std::size_t rounds) {
    std::vector<std::thread> vthread(nworks); // 线程池

    std::size_t totalCost = 0;

    for (std::size_t k = 0; k < nworks; ++k) {
        vthread[k] = std::thread([&]() {
            for (std::size_t j = 0; j < rounds; ++j) {
                std::size_t begin1 = clock();
                for (std::size_t i = 0; i < ntimes; i++) {
                    P1 *p1 = newElement<P1>();
                    deleteElement<P1>(p1);
                    P2 *p2 = newElement<P2>();
                    deleteElement<P2>(p2);
                    P3 *p3 = newElement<P3>();
                    deleteElement<P3>(p3);
                    P4 *p4 = newElement<P4>();
                    deleteElement<P4>(p4);
                }
                std::size_t end1 = clock();

                totalCost += end1 - begin1;
            }
        });
    }

    for (auto &t : vthread) {
        t.join();
    }

    std::cout << nworks << " 个线程并发执行 " << rounds << " 每轮次进行操作 " << "`newElement & deleteElement` "
              << ntimes << " 次，耗时 " << totalCost << "ms" << std::endl;
}

void BenchmarkNew(std::size_t ntimes, std::size_t nworks, std::size_t rounds) {
    std::vector<std::thread> vthread(nworks); // 线程池

    std::size_t totalCost = 0;

    for (std::size_t k = 0; k < nworks; ++k) {
        vthread[k] = std::thread([&]() {
            for (std::size_t j = 0; j < rounds; ++j) {
                std::size_t begin1 = clock();
                for (std::size_t i = 0; i < ntimes; i++) {
                    P1 *p1 = new P1;
                    delete p1;
                    P2 *p2 = new P2;
                    delete p2;
                    P3 *p3 = new P3;
                    delete p3;
                    P4 *p4 = new P4;
                    delete p4;
                }
                std::size_t end1 = clock();

                totalCost += end1 - begin1;
            }
        });
    }

    for (auto &t : vthread) {
        t.join();
    }

    std::cout << nworks << " 个线程并发执行 " << rounds << " 每轮次进行操作 `new & delete` " << ntimes << " 次，耗时 "
              << totalCost << "ms" << std::endl;
}

int main() {
    HashBucket::initMemoryPool();
    std::cout << "======================================TEST BEGIN=====================================" << std::endl;

    BenchmarkMemoryPool(100, 1, 10);
    BenchmarkNew(100, 1, 10);

    std::cout << "======================================TEST  END =====================================" << std::endl;
}